<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\Amap;
use app\common\Report;
use app\common\UsersService;
use app\model\Friends;
use app\model\FriendsComment;
use app\model\FriendsTags;
use app\model\FriendsUsers;
use app\model\HkArea;
use app\model\UsersRelated;
use app\model\UsersShield;
use app\Request;
use app\tool\GpsUtils;
use app\tool\Http;
use app\tool\ZhConvert;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\Exception;
use think\facade\Log;
use think\response\Json;

class FriendsController extends BaseController
{
    protected array $middleware = [
        'Login' => ['except' => ['index', 'tag_index', 'test', 'get_json','read','comment_list','map','map_detail']],
        'Location' => ['only' => ['index', '']],
    ];
	
	/**
	 * 屏蔽
	 * @param Request $request
	 * @return void
	 */
	function shield(Request $request)
	{
		$id = $request->post('id/d');
		UsersShield::create([
			'users_id'=>$request->users_id,
			'pro_id'=>$id,
			'type'=>'friends'
		]);
		writeJson();
	}

	
    /**
     * 活动交友-列表
     * @return Json
     */
    public function index(Request $request,mixed $tags_id, int $type, string $keyword, int $default, mixed $hk_area_id)
    {
	    $shield = UsersShield::where(['users_id'=>$request->users_id,'type'=>'friends'])->column('pro_id');
	    
	    $lat = self::$latitude;
        $lng = self::$longitude;
		$time = time();
        $rows = Friends::field("*,(play_start_time - $time) as play_start_time_text,(6371 * acos (cos ( radians($lat) ) * cos( radians( latitude ) ) * cos( radians(longitude) - radians( $lng ) ) + sin ( radians( $lat ) ) * sin( radians( latitude ) ))) AS distance")
            ->filter(function ($data) use($lat,$lng) {
                if (empty($lat) || empty($lng)) {
                    $data->distance_text = '';
                } else {
	                if (empty($data->latitude)||empty($data->longitude)){
		                $data->distance_text = '';
	                }else{
		                if ($data->distance == 0) {
			                $data->distance_text = '0m';
		                } elseif (0 < $data->distance && $data->distance < 1) {
			                $data->distance_text = bcmul((string)$data->distance, '1000') . 'm';
		                } else {
			                $data->distance_text = bcmul((string)$data->distance, '1', 1) . 'km';
		                }
	                }
                }

            })
	        ->whereNotIn('id', $shield)
            ->with(['users', 'tags'])
            ->where(['type' => $type])
	        ->when(!empty($hk_area_id)&&$hk_area_id!=3, function (Query $query) use ($hk_area_id) {
		        $query->whereFindInSet('hk_area_ids',$hk_area_id);
	        })
            ->when(!empty($keyword), function (Query $query) use ($keyword) {
                $query->whereLike('title|content', '%' . $keyword . '%');
            })
            ->when(!empty($tags_id), function (Query $query) use ($tags_id) {
                $query->whereFindInSet('tags_id', $tags_id);
            })
            ->when(!empty($default), function (Query $query) use ($default,$lat,$lng,$type) {
                switch ($default) {
                    case 1:
	                    if ($type == 1) {
		                    $query->order(['id' => 'desc']);
	                    } else {
		                    $query->order(['users_num' => 'desc','id'=>'desc']);
	                    }
                        break;
                    case 2:
                        $query->order(['browse'=>'desc']);
                        break;
                    case 3:
	                    if ($type == 1) {
		                    $query->order(['createtime' => 'desc']);
	                    } else {
		                    $query->order(['play_start_time_text'=>'asc'])->having('play_start_time_text>=0');
	                    }
                        break;
                    case 4:
                        $query->where('images', '<>', '');
                        break;
                    case 5:
                        if (empty($lat)||empty($lng)){
                            $query->order('createtime', 'desc');
                        }else{
                            $query->order('distance', 'desc');
                        }
                        break;
                }
            })
	        ->paginate()
	        ->items();
        writeJson($rows);
    }
	

	/**
	 * 地图
	 * @return Json
	 */
	public function map(float $latitude,float $longitude,int $type,int $distance, mixed $tags_id, string $keyword, int $default, mixed $hk_area_id)
	{
		$lat = $latitude;
		$lng = $longitude;
		$res = Friends::field("*,(6371 * acos (cos ( radians($lat) ) * cos( radians( latitude ) ) * cos( radians(longitude) - radians( $lng ) ) + sin ( radians( $lat ) ) * sin( radians( latitude ) ))) AS distance")
			->filter(function ($data) use($lat,$lng) {
				if (empty($lat) || empty($lng)) {
					$data->distance_text = '';
				} else {
					if ($data->distance == 0) {
						$data->distance_text = '0m';
					} elseif (0 < $data->distance && $data->distance < 1) {
						$data->distance_text = bcmul((string)$data->distance, '1000') . 'm';
					} else {
						$data->distance_text = bcmul((string)$data->distance, '1', 1) . 'km';
					}
				}
				
			})
			->when(!empty($type), function (Query $query) use ($type) {
				if ($type == 1) {
					$query->order(['id' => 'desc']);
				} else {
					$query->order(['users_num' => 'desc']);
				}
			})
			->when(!empty($hk_area_id)&&$hk_area_id!=3, function (Query $query) use ($hk_area_id) {
				$query->whereFindInSet('hk_area_ids',$hk_area_id);
			})
			->when(!empty($keyword), function (Query $query) use ($keyword) {
				$query->whereLike('title|content', '%' . $keyword . '%');
			})
			->when(!empty($tags_id), function (Query $query) use ($tags_id) {
				$query->whereFindInSet('tags_id', $tags_id);
			})
			->when(!empty($default), function (Query $query) use ($default,$lat,$lng) {
				switch ($default) {
					case 1:
						$query->order('id', 'desc');
						break;
					case 2:
						$query->order('hot', 'desc');
						break;
					case 3:
						$query->order('createtime', 'desc');
						break;
					case 4:
						$query->where('images', '<>', '');
						break;
					case 5:
						if (empty($lat)||empty($lng)){
							$query->order('createtime', 'desc');
						}else{
							$query->order('distance', 'asc');
						}
						break;
				}
			})
			->hidden(['content'])
			->where(['type' => $type])
			->having("distance<=$distance")
			->select();
		writeJson($res);
	}
	
    /**
     * 活动交友-分类列表
     */
    public function tag_index(int $type)
    {
        $FriendsTagsModle = new FriendsTags();
        $res = $FriendsTagsModle->where(['type' => $type])->order('id', 'desc')->select();
        writeJson($res);
    }

    /**
     * 活动交友-评论
     * @return \think\response\Json
     */
    function comment(Request $request)
    {
        $params = $request->param();
        $ip = $request->ip();
        $params['ip'] = $ip;
        $ip = Amap::ip($ip);
        $ip = json_decode($ip);
        if ($ip->status == 1) {
            $params['city'] = $ip->province;
        } else {
            $params['city'] = '未知';
        }
        $res = FriendsComment::create($params);
        foreach ($params['content'] as $v) {
            if ($v['type'] == 'at') {
                //@提醒  提醒接收人
                UsersRelated::create(['users_id' => $v['userId'], 'type' => 8, 'from_users_id' => $request->users_id, 'scene' => 'Friends', 'pro_id' => $res->id]);
            }
        }
        if (!empty($params['to_users_id'])) {
            //回复提醒  提醒接收人
            UsersRelated::create(['users_id' => $params['to_users_id'], 'type' => 1, 'from_users_id' => $request->users_id, 'scene' => 'Friends', 'pro_id' => $res->id]);
        } else {
            //评论提醒  提醒发布人
            $pro = Friends::find($params['friends_id']);
            UsersRelated::create(['users_id' => $pro->users_id, 'type' => 2, 'from_users_id' => $request->users_id, 'scene' => 'Friends', 'pro_id' => $res->id]);
        }
        $row = FriendsComment::with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
            $query->where(['users_id' => $request->users_id, 'type' => 'friends_comment']);
        }])->find($res->id);
        writeJson($row);
    }

    /**
     * 活动交友-发布
     * @param Request $request
     * @return Json
     */
    public function save(Request $request)
    {
        $ReportCheck = Report::check($request->users_id);
        if (!$ReportCheck) {
            writeJson(0,'信用分过低');
        }
		$params = $request->param();
	    if (!empty($params['longitude'])&&!empty($params['latitude'])){
		    $ids = HkArea::where([['top','>=',$params['latitude']],['bottom','<=',$params['latitude']],['left','<=',$params['longitude']],['right','>=',$params['longitude']]])->column('id');
		    $ids = implode(',',$ids);
		    $params['hk_area_ids'] = $ids;
	    }
	    
	    $res = Friends::create($params);
        $res = Friends::with(['users', 'tags'])->find($res->id);
        writeJson($res);
    }

    /**
     * 活动交友-活动-详情
     * @param Request $request
     * @param int $id
     * @return Json
     */
    public function read(Request $request, int $id)
    {
        $row = Friends::with([
            'tags',
            'users',
            'users_collect' => function (Query $query) use ($request) {
                $query->where(['users_id' => $request->users_id, 'type' => 'friends']);
            },
            'users_like' => function (Query $query) use ($request) {
                $query->where(['users_id' => $request->users_id, 'type' => 'friends']);
            },
            'join_users' => function (Query $query) {
                $query->with(['users'])->order(['id' => 'desc']);
            }])
            ->filter(function ($data) use ($request) {
                $data->is_join = FriendsUsers::where(['friends_id' => $data->id, 'users_id' => $request->users_id])->find() ? 1 : 0;//是否报名
            })
            ->find($id);
        UsersService::footmark($id, $request->users_id, 'friends');
	    event('FriendsIncBrowse', $id); //增加浏览数量
        writeJson($row);
    }
	
	/**
	 * 点赞
	 * @param Request $request
	 * @return Json
	 */
    function like(Request $request)
    {
        $id = $request->post('id');
        $res = UsersService::like($id, $request->users_id, 'friends');
        $res ? event('FriendsIncLike', $id) : event('FriendsDecLike', $id); //增加/减少  点赞数量
        if ($res) {
            $pro = Friends::find($id);
            UsersRelated::create(['users_id' => $pro->users_id, 'type' => 3, 'from_users_id' => $request->users_id, 'scene' => 'Friends', 'pro_id' => $id]);
        }
        writeJson($res);
    }
	
	/**
	 * 收藏
	 * @param Request $request
	 * @return Json
	 */
    function collect(Request $request)
    {
        $id = $request->post('id');
        $res = UsersService::collect($id, $request->users_id, 'friends');
        $res ? event('FriendsIncCollect', $id) : event('FriendsDecCollect', $id); //增加/减少  收藏数量
        if ($res) {
            $pro = Friends::find($id);
            UsersRelated::create(['users_id' => $pro->users_id, 'type' => 7, 'from_users_id' => $request->users_id, 'scene' => 'Friends', 'pro_id' => $id]);
        }
        writeJson($res);
    }


    /**
     * 评论点赞
     * @param Request $request
     * @return Json
     */
    function comment_like(Request $request)
    {
        $id = $request->param('id');
        $res = UsersService::like($id, $request->users_id, 'friends_comment');
        $res ? event('FriendsCommentIncLike', $id) : event('FriendsCommentDecLike', $id); //增加/减少  点赞数量
        if ($res) {
            $pro = FriendsComment::find($id);
            UsersRelated::create(['users_id' => $pro->users_id, 'type' => 4, 'from_users_id' => $request->users_id, 'scene' => 'Friends', 'pro_id' => $id]);
        }
        writeJson($res);
    }
	
	
	/**
	 * 评论列表
	 * @param int $friends_id
	 * @param mixed $comment_id
	 * @param Request $request
	 * @return Json
	 */
    function comment_list(int $friends_id, mixed $comment_id, Request $request)
    {

        $top_id = 0;
        if (!empty($comment_id)) {
            $row = FriendsComment::find($comment_id);
            if ($row->pid == 0) {
                //顶级评论 放在第一条
                $top_id = $row->id;
            } else {
                //子评论 找出顶级评论
                $row = FriendsComment::find($row->pid);
                $top_id = $row->id;
            }
        }

        $rows = FriendsComment::where(['pid' => 0, 'friends_id' => $friends_id])
            ->withCount('comment')
            ->with([
                'users',
                'users_like' => function (Query $query) use ($request) {
                    $query->where(['users_id' => $request->users_id, 'type' => 'friends_comment']);
                },
                'comment' => function (Query $query) use ($request, $comment_id) {
                    $query
                        ->with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
                            $query->where(['users_id' => $request->users_id, 'type' => 'friends_comment']);
                        }])
                        ->when(!empty($comment_id), function (Query $query) use ($comment_id) {
                            $query->field("*,IF(id = $comment_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
                        }, function (Query $query) {
                            $query->order(['id' => 'desc']);
                        })
                        ->limit($this->comment_list_rows);
                }])
            ->when(!empty($comment_id), function (Query $query) use ($top_id) {
                $query->field("IF(id = $top_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
            }, function (Query $query) {
                $query->order(['id' => 'desc']);
            })
            ->paginate()
            ->items();
        writeJson($rows);
    }
	
	
	/**
	 * 评论详情
	 * @param Request $request
	 * @param mixed $comment_id
	 * @param int $id
	 * @return Json
	 */
    function comment_detail(Request $request, mixed $comment_id, int $id)
    {
        $child = false;
        if (!empty($comment_id)) {
            $row = FriendsComment::find($comment_id);
            if ($row->pid != 0) {
                //二级评论
                $child = true;
            }
        }
        $rows = FriendsComment::with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
            $query->where(['users_id' => $request->users_id, 'type' => 'friends_comment']);
        }])
            ->where(['pid' => $id])
            ->when($child, function (Query $query) use ($comment_id) {
                $query->where('id', '<>', $comment_id);
            })
            ->order(['id' => 'desc'])
            ->paginate($this->comment_detail_rows)
            ->items();
        writeJson($rows);
    }


    /**
     * 活动交友-报名
     * @param Request $request
     * @param int $friends_id
     * @return Json
     */
    function play_join(Request $request, int $friends_id)
    {
        $ReportCheck = Report::check($request->users_id);
        if (!$ReportCheck) {
            writeJson(0,'信用分过低');
        }
        $row = FriendsUsers::where(['friends_id' => $friends_id, 'users_id' => $request->users_id])->find();
        if ($row) {
	        writeJson(0,'已经报名');
        }
		$friends = Friends::findOrFail($friends_id);
	    if (empty($friends->end_time)){
		    writeJson(0,'该活动不能报名');
	    }
		if ($friends->end_time<=time()){
			writeJson(0,'活动已结束');
		}
	    FriendsUsers::create($request->param());
	    $friends->users_num +=1;
	    $friends->save();
        writeJson();
    }


    /**
     * 活动交友-取消报名
     * @param Request $request
     * @param $friends_id
     */
    function un_play_join(Request $request, $friends_id)
    {
        $FriendsUsersModel = new FriendsUsers();
        $res = $FriendsUsersModel->where(['friends_id' => $friends_id, 'users_id' => $request->users_id])->find();
        if (!$res) {
	        writeJson(0,'没有报名');
        }
        $res->delete();
        Friends::find($friends_id)->dec('users_num')->update();
        writeJson();
    }
	
	
	public function map_detail()
	{
		$params = $this->request->param(); //type类型:1=交友,2=活动 $lat $lng
		$lat = $params['latitude'];
		$lng = $params['longitude'];
		$res = Friends::field("*,(6371 * acos (cos ( radians($lat) ) * cos( radians( latitude ) ) * cos( radians(longitude) - radians( $lng ) ) + sin ( radians( $lat ) ) * sin( radians( latitude ) ))) AS distance")
			->with(['users', 'tags'])
			->filter(function ($data) use($lat,$lng) {
				if (empty($lat) || empty($lng)) {
					$data->distance_text = '';
				} else {
					if ($data->distance == 0) {
						$data->distance_text = '0m';
					} elseif (0 < $data->distance && $data->distance < 1) {
						$data->distance_text = bcmul(number_format($data->distance,6), '1000') . 'm';
					} else {
						$data->distance_text = bcmul((string)$data->distance, '1', 1) . 'km';
					}
				}
			})
			->where(['type' => $params['type'],'longitude'=>$lng,'latitude'=>$lat])
			->select();
		writeJson($res);
	}

    /**
     * 批量删除
     * @param Request $request
     * @return Json
     */
    public function delete(Request $request)
    {
        $ids = $request->post('ids');
        Friends::whereIn('id', $ids)->where(['users_id' => $request->users_id])->select()->delete();
        writeJson();
    }

    function get_json()
    {
	    
	    ignore_user_abort(true); // 关闭浏览器 继续执行
	    set_time_limit(0); // 执行时间为无限制
	    ini_set("memory_limit","-1");
	    $res = Http::get('https://www.ogcio.gov.hk/sc/our_work/business/industry_support/event_calendar/event-calendar.json');
	    $res = json_decode($res);
	    foreach ($res as $k) {
		    $row = Friends::where(['type' => 2, 'unique' => $k->ID])->find();
		    if (!$row) {
			    $data=[
				    'users_id' => 3,
				    'tags_id' => 12,
				    'type' => 2,
				    'title' => $k->FULL_NAME_SC,
				    'play_start_time' => strtotime($k->EVENT_START_DATE),
				    'play_end_time' => strtotime($k->EVENT_END_DATE),
				    'address' => $k->VENUE_SC,
				    'content' =>
					    '<p>' . $k->EVENT_TIME_DETAIL_SC . '</p>' .
					    '<p>' . $k->DESCRIPTION_SC . '</p>' .
					    '<p>' . $k->LINK_SC . '</p>' .
					    '<p><a href=' . $k->REMARK_SC . '>' . $k->REMARK_SC . '</a></p>',
				    'unique' => $k->ID
			    ];
			    if (!empty($k->VENUE_SC)){
				    $point = Http::get("https://geodata.gov.hk/gs/api/v1.0.0/locationSearch",['q'=>$k->VENUE_SC]);
				    $point = json_decode($point);
				    if (!empty($point)){
					    $point = $point[0];
					    list($lng,$lat) = GpsUtils::hk80ToWgs84($point->x,$point->y);
					    $data['longitude']=$lng;
					    $data['latitude']=$lat;
					    $ids = HkArea::where([['top', '>=', $lat], ['bottom', '<=', $lat], ['left', '<=', $lng], ['right', '>=', $lng]])->column('id');
					    $ids = implode(',', $ids);
					    $data['hk_area_ids'] = $ids;
				    }
			    }
			    Friends::create($data);
		    }
	    }
	    
	    $res = Http::get('https://www1.investhk.gov.hk/api/upcoming-events');
	    $res = json_decode($res);
	    $res = $res->_item;
	    foreach ($res as $k) {
		    $row = Friends::where(['type' => 2, 'unique' => $k->title])->find();
		    if (!$row) {
			    
			    $data=[
				    'users_id' => 3,
				    'tags_id' => 12,
				    'type' => 2,
				    'title' => $k->title,
				    'images' => $k->image,
				    'play_start_time' => strtotime($k->start_date),
				    'play_end_time' => strtotime($k->end_date),
				    'address' => $k->location,
				    'content' => '<p>' . $k->summary . '</p>' . '<p><a href=' . $k->link . '>' . $k->link . '</a></p>',
				    'unique' => $k->title,
			    ];
//	            if (!empty($k->location)){
//		            $point = Http::get("https://geodata.gov.hk/gs/api/v1.0.0/locationSearch",['q'=>$k->location]);
//		            $point = json_decode($point);
//		            $point = $point[0];
//		            list($lng,$lat) = GpsUtils::hk80ToWgs84($point->x,$point->y);
//		            $data['longitude']=$lng;
//		            $data['latitude']=$lat;
//	            }
			    Friends::create($data);
		    }
	    }
	    
	    $res = Http::get('https://www.lcsd.gov.hk/datagovhk/event/leisure_prog.json');
	    $res = json_decode($res);
	    foreach ($res as $k) {
		    $row = Friends::where(['type' => 2, 'unique' => $k->PGM_CODE])->find();
		    if (!$row) {
			    $data = [
				    'users_id' => 3,
				    'tags_id' => 12,
				    'type' => 2,
				    'title' => ZhConvert::zh_auto($k->TC_PGM_NAME,'zh-hant'),
				    'start_time' => strtotime($k->ENROL_START_DATE),
				    'end_time' => strtotime($k->ENROL_END_DATE),
				    
				    'play_start_time' => strtotime($k->PGM_START_DATE),
				    'play_end_time' => strtotime($k->PGM_END_DATE),
				    'address' =>ZhConvert::zh_auto($k->TC_DISTRICT . $k->TC_VENUE,'zh-hant'),
				    'content' =>
					    ($k->TC_DAY ? '<p>' . ZhConvert::zh_auto($k->TC_DAY,'zh-hant') . '</p>' : '') .
					    ($k->TC_NOTES_1 ? '<p>' .  ZhConvert::zh_auto($k->TC_NOTES_1,'zh-hant') . '</p>' : '') .
					    ($k->TC_NOTES_2 ? '<p>' .  ZhConvert::zh_auto($k->TC_NOTES_2,'zh-hant') . '</p>' : '') .
					    ($k->SC_URL ? '<p><a href=' . $k->SC_URL . '>' . $k->SC_URL . '</a></p>' : ''),
				    'unique' => $k->PGM_CODE,
			    ];
			    if (!empty($k->TC_DISTRICT)||!empty($k->TC_VENUE)){
				    $point = Http::get("https://geodata.gov.hk/gs/api/v1.0.0/locationSearch",['q'=>$k->TC_DISTRICT . $k->TC_VENUE]);
				    $point = json_decode($point);
				    if (!empty($point)){
					    $point = $point[0];
					    list($lng,$lat) = GpsUtils::hk80ToWgs84($point->x,$point->y);
					    $data['longitude']=$lng;
					    $data['latitude']=$lat;
					    $ids = HkArea::where([['top', '>=', $lat], ['bottom', '<=', $lat], ['left', '<=', $lng], ['right', '>=', $lng]])->column('id');
					    $ids = implode(',', $ids);
					    $data['hk_area_ids'] = $ids;
				    }
			    }
			    Friends::create($data);
		    }
	    }
	    
	    $res = Http::get('https://www.lcsd.gov.hk/datagovhk/event/events.xml');
	    $address = Http::get('https://www.lcsd.gov.hk/datagovhk/event/venues.xml');
	    $res = simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);
	    $address = simplexml_load_string($address, 'SimpleXMLElement', LIBXML_NOCDATA);
	    $res = json_encode($res);
	    $res = json_decode($res);
	
	    $address = json_encode($address);
	    $address = json_decode($address);
	    $res = $res->event;
	    
	    $address = $address->venue;
	    // 定义要查找的是哪个键的值
	    $address = array_column($address, '@attributes', 'venuec');
	    $address = array_flip(array_combine(array_keys($address), array_column($address, 'id')));
	    foreach ($res as $k) {
				
			    $row = Friends::where(['type' => 2, 'unique' => $k->{"@attributes"}->id])->find();
			    if (!$row) {
				    try {
					    $data=[
						    'users_id' => 3,
						    'tags_id' => 12,
						    'type' => 2,
						    'title' => ZhConvert::zh_auto($k->titlec,'zh-hant'),
						    'play_start_time' => strtotime($k->predateC),
						    'play_end_time' => strtotime($k->predateC),
						    'address' => $k->venueid ? $address[$k->venueid] : '',
						    'content' =>
							    (gettype($k->progtimec) == 'string' ? '<p>' . ZhConvert::zh_auto($k->progtimec,'zh-hant') . '</p>' : '') .
							    (gettype($k->agelimitc) == 'string' ? '<p>' . ZhConvert::zh_auto($k->agelimitc,'zh-hant') . '</p>' : '') .
							    (gettype($k->descc) == 'string' ? '<p>' . ZhConvert::zh_auto($k->descc,'zh-hant') . '</p>' : '') .
							    (gettype($k->remarkc) == 'string' ? '<p>' . ZhConvert::zh_auto($k->remarkc,'zh-hant') . '</p>' : '') .
							    (gettype($k->urlc) == 'string' ? '<p><a href=' . $k->urlc . '>' . $k->urlc . '</a></p>' : ''),
						    'unique' => $k->{"@attributes"}->id,
					    ];
					    
				    }catch (\Throwable $e){
						continue;
				    }
				
				
				    if (!empty($k->venueid)){
					    $point = Http::get("https://geodata.gov.hk/gs/api/v1.0.0/locationSearch",['q'=>$address[$k->venueid]]);
					    $point = json_decode($point);
					    if (!empty($point)){
						    $point = $point[0];
						    list($lng,$lat) = GpsUtils::hk80ToWgs84($point->x,$point->y);
						    $data['longitude']=$lng;
						    $data['latitude']=$lat;
						    $ids = HkArea::where([['top', '>=', $lat], ['bottom', '<=', $lat], ['left', '<=', $lng], ['right', '>=', $lng]])->column('id');
						    $ids = implode(',', $ids);
						    $data['hk_area_ids'] = $ids;
					    }
				    }
				    Friends::create($data);
			    }
		 
		   
	    }
	    writeJson();
    }


}
